import app from '../../index';
import api from '../../utils/request';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponList: [],
    locationShow: true,
    showCouponContent: false,
    form: {
      limitType: '0',
      merchantId: 'T35202209070000001',
      longitude: '',
      latitude: ''
    },

    emptyFlag: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getData();
    this.setData({
      showCouponContent: true
    })
  },

  getData() {
    api.post('CL040109', {
      data: this.data.form
    }).then(res => {
      if (res.couponActivityInfoList && res.couponActivityInfoList.length > 0) {
        for (let i = 0; i < res.couponActivityInfoList.length; i++) {
          res.couponActivityInfoList[i].validEndDate = res.couponActivityInfoList[i].validEndDate.slice(0, 10)
          res.couponActivityInfoList[i]['alreadyReceived'] = false
        }
        this.setData({
          couponList: res.couponActivityInfoList,
          emptyFlag: false
        })
      } else {
        this.setData({
          emptyFlag: true
        })
      }
    })
  },

  /**
   * 立即领取
   */
  receiveCoupon(e) {
    wx.showLoading({
      title: '领取中...',
      mask: true
    })
    api.post('CL040110', {
      data: {
        couponActivityIds: [e.currentTarget.dataset.id]
      }
    }).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '领取成功！',
        mask: true,
        success: () => {}
      })
      let couponObj = this.data.couponList[e.currentTarget.dataset.idx]
      couponObj.alreadyReceived = true
      this.setData({
        ['couponList[' + e.currentTarget.dataset.idx + ']']: couponObj
      })
    })
  },

  /**
   * 使用规则
   */
  useRule(e) {
    app.router('../couponRule/couponRule?item=' + JSON.stringify(e.currentTarget.dataset.item));
  },

})